/**
 * 认证服务
 * 处理用户登录、注册、验证码等认证相关API
 * 
 * 功能说明：
 * - 用户登录（手机号验证码、身份证密码）
 * - 发送短信验证码
 * - 用户注册
 * - 密码重置
 * - 登录状态验证
 * 
 * @author 项目开发团队
 * @version 1.0.0
 */

import axios from 'axios'

// 创建axios实例
const authAPI = axios.create({
  baseURL: '/api/auth',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
authAPI.interceptors.request.use(
  (config) => {
    // 添加认证token
    const token = localStorage.getItem('authToken')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
authAPI.interceptors.response.use(
  (response) => {
    return response.data
  },
  (error) => {
    // 处理认证错误
    if (error.response?.status === 401) {
      localStorage.removeItem('authToken')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

/**
 * 用户登录
 * @param {Object} credentials - 登录凭据
 * @param {string} credentials.type - 登录类型 'phone' | 'idcard'
 * @param {string} credentials.phone - 手机号（手机号登录时必填）
 * @param {string} credentials.smsCode - 短信验证码（手机号登录时必填）
 * @param {string} credentials.idCard - 身份证号（身份证登录时必填）
 * @param {string} credentials.password - 密码（身份证登录时必填）
 * @returns {Promise<Object>} 登录结果
 */
export const login = async (credentials) => {
  try {
    const response = await authAPI.post('/login', credentials)
    
    // 保存token到localStorage
    if (response.data?.token) {
      localStorage.setItem('authToken', response.data.token)
    }
    
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '登录失败')
  }
}

/**
 * 发送短信验证码
 * @param {string} phone - 手机号
 * @returns {Promise<Object>} 发送结果
 */
export const sendSmsCode = async (phone) => {
  try {
    const response = await authAPI.post('/sms/send', { phone })
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '发送验证码失败')
  }
}

/**
 * 验证短信验证码
 * @param {string} phone - 手机号
 * @param {string} code - 验证码
 * @returns {Promise<Object>} 验证结果
 */
export const verifySmsCode = async (phone, code) => {
  try {
    const response = await authAPI.post('/sms/verify', { phone, code })
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '验证码验证失败')
  }
}

/**
 * 用户注册
 * @param {Object} userData - 用户注册数据
 * @param {string} userData.phone - 手机号
 * @param {string} userData.smsCode - 短信验证码
 * @param {string} userData.password - 密码
 * @param {string} userData.confirmPassword - 确认密码
 * @param {string} userData.realName - 真实姓名
 * @param {string} userData.idCard - 身份证号
 * @returns {Promise<Object>} 注册结果
 */
export const register = async (userData) => {
  try {
    const response = await authAPI.post('/register', userData)
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '注册失败')
  }
}

/**
 * 忘记密码
 * @param {string} phone - 手机号
 * @returns {Promise<Object>} 发送结果
 */
export const forgotPassword = async (phone) => {
  try {
    const response = await authAPI.post('/forgot-password', { phone })
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '发送重置密码链接失败')
  }
}

/**
 * 重置密码
 * @param {Object} resetData - 重置密码数据
 * @param {string} resetData.phone - 手机号
 * @param {string} resetData.smsCode - 短信验证码
 * @param {string} resetData.newPassword - 新密码
 * @param {string} resetData.confirmPassword - 确认新密码
 * @returns {Promise<Object>} 重置结果
 */
export const resetPassword = async (resetData) => {
  try {
    const response = await authAPI.post('/reset-password', resetData)
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '重置密码失败')
  }
}

/**
 * 验证登录状态
 * @returns {Promise<Object>} 用户信息
 */
export const verifyAuth = async () => {
  try {
    const response = await authAPI.get('/verify')
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '验证登录状态失败')
  }
}

/**
 * 刷新token
 * @returns {Promise<Object>} 新的token
 */
export const refreshToken = async () => {
  try {
    const response = await authAPI.post('/refresh')
    
    // 更新token
    if (response.data?.token) {
      localStorage.setItem('authToken', response.data.token)
    }
    
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '刷新token失败')
  }
}

/**
 * 用户登出
 * @returns {Promise<Object>} 登出结果
 */
export const logout = async () => {
  try {
    await authAPI.post('/logout')
    
    // 清除本地token
    localStorage.removeItem('authToken')
    
    return { success: true }
  } catch (error) {
    // 即使API调用失败，也清除本地token
    localStorage.removeItem('authToken')
    throw new Error(error.response?.data?.message || '登出失败')
  }
}

/**
 * 修改密码
 * @param {Object} passwordData - 密码修改数据
 * @param {string} passwordData.oldPassword - 旧密码
 * @param {string} passwordData.newPassword - 新密码
 * @param {string} passwordData.confirmPassword - 确认新密码
 * @returns {Promise<Object>} 修改结果
 */
export const changePassword = async (passwordData) => {
  try {
    const response = await authAPI.post('/change-password', passwordData)
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '修改密码失败')
  }
}

/**
 * 获取用户权限
 * @returns {Promise<Object>} 用户权限信息
 */
export const getUserPermissions = async () => {
  try {
    const response = await authAPI.get('/permissions')
    return response.data
  } catch (error) {
    throw new Error(error.response?.data?.message || '获取权限失败')
  }
}

// 模拟API数据（开发环境使用）
const mockAPI = {
  login: async (credentials) => {
    // 模拟网络延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 模拟登录验证
    if (credentials.type === 'phone') {
      if (!credentials.phone || !credentials.smsCode) {
        throw new Error('手机号和验证码不能为空')
      }
      if (!/^1[3-9]\d{9}$/.test(credentials.phone)) {
        throw new Error('手机号格式不正确')
      }
      // 验证短信验证码
      const storedCode = sessionStorage.getItem('smsCode')
      const storedPhone = sessionStorage.getItem('smsPhone')
      const storedTime = sessionStorage.getItem('smsTime')
      
      // 检查验证码是否过期（5分钟）
      if (storedTime && Date.now() - parseInt(storedTime) > 5 * 60 * 1000) {
        sessionStorage.removeItem('smsCode')
        sessionStorage.removeItem('smsPhone')
        sessionStorage.removeItem('smsTime')
        throw new Error('验证码已过期，请重新获取')
      }
      
      // 检查手机号是否匹配
      if (storedPhone !== credentials.phone) {
        throw new Error('手机号不匹配')
      }
      
      // 检查验证码是否正确
      if (storedCode !== credentials.smsCode) {
        throw new Error('验证码错误')
      }
      
      // 验证成功后清除存储的验证码
      sessionStorage.removeItem('smsCode')
      sessionStorage.removeItem('smsPhone')
      sessionStorage.removeItem('smsTime')
    } else if (credentials.type === 'idcard') {
      if (!credentials.idCard || !credentials.password) {
        throw new Error('身份证号和密码不能为空')
      }
      if (!/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/.test(credentials.idCard)) {
        throw new Error('身份证号格式不正确')
      }
      // 身份证登录密码验证（开发环境固定密码：123456）
      if (credentials.password !== '123456') {
        throw new Error('密码错误，请输入：123456')
      }
    }
    
    // 返回模拟用户数据
    return {
      success: true,
      token: 'mock-jwt-token-' + Date.now(),
      user: {
        id: 'U001',
        username: 'StarYun',
        realName: '王*柯',
        phone: credentials.phone || '138****8888',
        idCard: credentials.idCard || '110101199001011234',
        avatar: '/api/avatar',
        gender: '女',
        age: 28
      }
    }
  },
  
  sendSmsCode: async (phone) => {
    await new Promise(resolve => setTimeout(resolve, 500))
    
    if (!/^1[3-9]\d{9}$/.test(phone)) {
      throw new Error('手机号格式不正确')
    }
    
    // 生成6位随机验证码
    const smsCode = Math.floor(100000 + Math.random() * 900000).toString()
    
    // 打印验证码到控制台（开发环境）
    console.log('='.repeat(50))
    console.log('📱 短信验证码')
    console.log('='.repeat(50))
    console.log(`手机号: ${phone}`)
    console.log(`验证码: ${smsCode}`)
    console.log(`时间: ${new Date().toLocaleString()}`)
    console.log('='.repeat(50))
    
    // 将验证码存储到sessionStorage，用于验证
    sessionStorage.setItem('smsCode', smsCode)
    sessionStorage.setItem('smsPhone', phone)
    sessionStorage.setItem('smsTime', Date.now().toString())
    
    return {
      success: true,
      message: '验证码已发送',
      code: smsCode // 开发环境返回验证码
    }
  },
  
  verifyAuth: async () => {
    await new Promise(resolve => setTimeout(resolve, 300))
    
    const token = localStorage.getItem('authToken')
    if (!token) {
      throw new Error('未登录')
    }
    
    return {
      success: true,
      user: {
        id: 'U001',
        username: 'StarYun',
        realName: '王*柯',
        phone: '138****8888',
        idCard: '110101199001011234',
        avatar: '/api/avatar',
        gender: '女',
        age: 28
      }
    }
  }
}

// 开发环境使用模拟API
const isDevelopment = process.env.NODE_ENV === 'development'

export const authService = {
  login: isDevelopment ? mockAPI.login : login,
  sendSmsCode: isDevelopment ? mockAPI.sendSmsCode : sendSmsCode,
  verifySmsCode: isDevelopment ? mockAPI.verifySmsCode : verifySmsCode,
  register: isDevelopment ? mockAPI.register : register,
  forgotPassword: isDevelopment ? mockAPI.forgotPassword : forgotPassword,
  resetPassword: isDevelopment ? mockAPI.resetPassword : resetPassword,
  verifyAuth: isDevelopment ? mockAPI.verifyAuth : verifyAuth,
  refreshToken: isDevelopment ? mockAPI.refreshToken : refreshToken,
  logout: isDevelopment ? mockAPI.logout : logout,
  changePassword: isDevelopment ? mockAPI.changePassword : changePassword,
  getUserPermissions: isDevelopment ? mockAPI.getUserPermissions : getUserPermissions
}
